<!--
@description    添加树节点
@author         秦俊强
@email          458112865@qq.com
@create         2020-03-14 18:10
-->

<template>
  <div class="node-box">
    <div class="item-box">
      <div class="title">父级指标：</div>
      <div class="content-form">
        <a-tree-select :treeData="newSelectTree" :treeDefaultExpandAll="true"
                       :dropdownStyle="{ 'max-height': '300px', 'overflow': 'auto' }"
                       v-model="nodeInfo.parentKey"></a-tree-select>
      </div>
    </div>

    <div class="item-box">
      <div class="title">新增指标名称：</div>
      <div class="content-form">
        <a-input v-model="nodeInfo.title" />
      </div>
    </div>

    <div class="item-box">
      <div class="title">新增指标类型：</div>
      <div class="content-form">
        <a-radio-group v-model="nodeInfo.type">
          <a-radio :value="'index'">指标</a-radio>
          <a-radio :value="'indexValue'">数据项</a-radio>
        </a-radio-group>
      </div>
    </div>
  </div>
</template>



<script>
  export default {
    props: {
      selectTree: null,
      autoKey: ''
    },

    data() {
      return {
        newSelectTree: this.initAddNodeTreeData(this.selectTree),
        nodeInfo: {
          parentKey: this.autoKey,
          title: '',
          type: 'index'
        }
      }
    },

    created() {
      // 监听 autoKey 的变化
      this.$watch('autoKey', () => { this.nodeInfo.parentKey = this.autoKey; });
    },

    methods: {

      /* 更新树 */
      updateNewSelectTree(tree) {
        this.newSelectTree = this.initAddNodeTreeData(tree);
      },

      /* 初始化弹窗下拉选择的树结构，因为添加的时候不能让用户选叶子节点 */
      initAddNodeTreeData(tree) {
        let newTree = [];

        // 从数组最后一个开始循环，因为涉及删除操作
        for (let i = tree.length - 1; i >= 0; i--) {
          let item = tree[i];

          if (item.type !== 'indexValue') {
            // 将数组放在最前面
            newTree.unshift({
              key: item.key,
              title: item.title,
              code: item.code,
              value: item.key,
              type: item.type
            });

            // 因为是 unshift，所以永远是第 0 个
            if (item.children && item.children.length > 0) {
              newTree[0]['children'] = [];
              newTree[0]['children'] = this.initAddNodeTreeData(item.children);
            }
          }
        }

        return newTree;
      }

    }
  }
</script>



<style lang="less" scoped>
  .node-box {
    padding: 3% 10%;

    .item-box {
      overflow: hidden;
      margin-bottom: 20px;

      .title, .content-form { float: left; }
      .title { width: 30%; }
      .content-form { width: 65% }

      .title, /deep/.ant-radio-group { line-height: 32px; }
    }

    /deep/.ant-select {
      width: 100%;
    }
  }
</style>
